package cn.sdhuijin.vms.controller;

import javax.inject.Inject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.sdhuijin.vms.controller.comand.LoginCommand;
import cn.sdhuijin.vms.model.User;
import cn.sdhuijin.vms.service.IUserService;

@Controller
public class IndexController {
	@Inject
	IUserService userService;

	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login(@ModelAttribute LoginCommand loginCommand) {
		return "login";
	}

	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout() {
		userService.logout();
		return "redirect:/";
	}

	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String login(@Validated LoginCommand loginCommand,
			BindingResult error, Model model) {
		if (error.hasErrors()) {
			return "login";
		}
		User user = new User();
		user.setUsername(loginCommand.getUsername());
		user.setPassword(loginCommand.getPassword());
		try {
			userService.login(user, loginCommand.getRememberMe());
			SecurityUtils.getSubject().getSession().setTimeout(-1000l); // 永不过期
		} catch (AuthenticationException e) {
			model.addAttribute("success", false);
			model.addAttribute("msg", "用户名或密码错误。");
			return "login";
		}
		return "redirect:/";
	}

	@RequestMapping(value = { "", "index" }, method = RequestMethod.GET)
	public String index() {
		return "index";
	}
}
